package com.sky.sky_server.controller.user;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sky.sky_common.constant.JwtRoleConstant;
import com.sky.sky_common.result.Result;
import com.sky.sky_common.util.JwtService;
import com.sky.sky_pojo.dto.UserLoginDTO;
import com.sky.sky_pojo.dto.UserLoginVO;
import com.sky.sky_pojo.entity.User;
import com.sky.sky_server.service.impl.UserServiceImpl;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user/user") // /user/user第一个代表用户端，第二个代表用户模块
@Slf4j
public class UserController {
    
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private JwtService jwtService;

    /**
     * 微信登录
     * @param userfLoginVO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userfLoginDTO) {
        // 获取当前登录的用户信息
        log.info("用户登录，用户信息：{}", userfLoginDTO);
        User user = userServiceImpl.wxLogin(userfLoginDTO);

        Map<String, Object> claims = Map.of(
            "id", user.getId(),
            "openid", user.getOpenid()
        );
        
        String token = jwtService.genJwtToken(user.getOpenid(), claims, JwtRoleConstant.USER);
        UserLoginVO userLoginVO = new UserLoginVO(user.getId(), user.getOpenid(), token);

        return Result.success(userLoginVO);
    }

    /**
     * 网页用户端登录测试接口
     */
    @PostMapping("/web/login")
    public Result webLogin() {
        log.info("网页端用户登录，测试接口，发放key");
        Map<String, Object> claims = Map.of(
            "id", "888",
            "ipenid", "888"
        );
        String token = jwtService.genJwtToken("888", claims, JwtRoleConstant.USER);
        UserLoginVO userLoginVO = new UserLoginVO(Long.parseLong("888"), "888", token);
        return Result.success(userLoginVO);
    }

}
